<template>
  <div class="law-list-page">
    <!-- 上方搜索 card -->
    <el-card
      class="search-card"
      style="display: flex; width: 100%; justify-content: space-between"
    >
      <div class="search-row">
        <div class="search-fields">
          <el-form :inline="true">
            <el-form-item label="法律法规名称：">
              <el-input
                v-model="searchForm.lawName"
                placeholder="请输入法律法规名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="正文：">
              <el-input
                v-model="searchForm.responsibilities"
                placeholder="请输入正文"
                clearable
              />
            </el-form-item>

            <el-form-item label="法条数：">
              <el-input
                v-model="searchForm.rulesNumber"
                placeholder="请输入法条数"
                clearable
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="search-actions">
          <el-button type="primary" @click="onSearch">搜索</el-button>
          <el-button
            type="primary"
            @click="onAdd"
            :disabled="!hasLawOperatePermission"
            >新增</el-button
          >
        </div>
      </div>
    </el-card>

    <!-- 下方列表 card -->
    <el-card class="list-card">
      <div v-loading="loading" class="law-list">
        <div v-for="(item, idx) in lawList" :key="item.id" class="law-item">
          <div class="law-item-main">
            <div class="law-item-left">
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  margin-bottom: 12px;
                "
              >
                <div
                  class="law-title"
                  v-html="
                    highlightText(
                      item.lawName,
                      searchForm.lawName,
                      searchForm.rulesNumber,
                      searchForm.responsibilities
                    ) +
                    (item.rulesNumber
                      ? ' ' +
                        highlightText(
                          String(item.rulesNumber),
                          searchForm.lawName,
                          searchForm.rulesNumber,
                          searchForm.responsibilities
                        )
                      : '')
                  "
                ></div>
                <div class="law-meta law-effective">
                  生效日期: <b>{{ formatDate(item.failureTime) }}</b>
                </div>
              </div>

              <div class="law-content-wrapper">
                <div v-if="isOverflowMap[item.id]" class="scroll-tip"></div>
                <div
                  class="law-content"
                  v-html="
                    highlightText(
                      item.responsibilities,
                      searchForm.lawName,
                      searchForm.rulesNumber,
                      searchForm.responsibilities
                    )
                  "
                  :ref="(el) => setLawContentRef(el, item.id)"
                ></div>
              </div>
            </div>
            <div class="law-item-right">
              <div class="law-dates-row">
                <div class="law-meta law-create">
                  创建日期: <b>{{ formatDate(item.createTime) }}</b>
                </div>
              </div>
              <div class="law-actions">
                <el-button
                  size="large"
                  class="edit-btn"
                  @click="onEdit(item)"
                  :disabled="!hasLawOperatePermission"
                  >编辑</el-button
                >
                <el-button
                  size="large"
                  class="delete-btn"
                  plain
                  :disabled="!hasLawOperatePermission"
                  @click="handleDelete(item)"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
          <el-divider class="law-divider" />
        </div>
      </div>
      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="prev, pager, next, sizes, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="onPageSizeChange"
          @current-change="onPageChange"
          :page-sizes="[10, 20, 50]"
        />
      </div>
    </el-card>

    <LawModal
      v-model:visible="modalVisible"
      :isEdit="isEdit"
      :data="currentLaw"
      @submit="handleModalSubmit"
    />
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, computed, onMounted } from "vue";
import LawModal from "./modal.vue";
import "./index.scss";
import useUserStore from "@/store/modules/user";
import { ElMessageBox, ElMessage } from "element-plus";
import { getList, deleteLaw } from "./services";

const searchForm = ref({ lawName: "", rulesNumber: "", responsibilities: "" });

const lawList = ref([]);

const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// 弹框控制
const modalVisible = ref(false);
const isEdit = ref(false);
const currentLaw = ref({});

const userStore = useUserStore();
const userRoles = userStore.roles || [];
const hasLawOperatePermission = computed(
  () => userRoles.includes("jd") || userRoles.includes("admin")
);

const loading = ref(false);

onMounted(() => {
  getListData();
});

const getListData = async () => {
  loading.value = true;
  try {
    const res = await getList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      lawName: searchForm.value.lawName,
      rulesNumber: searchForm.value.rulesNumber,
      responsibilities: searchForm.value.responsibilities,
    });
    lawList.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {}
  loading.value = false;
};

function onSearch() {
  currentPage.value = 1;
  getListData();
}

function onAdd() {
  isEdit.value = false;
  currentLaw.value = {};
  modalVisible.value = true;
}

function onEdit(item) {
  isEdit.value = true;
  currentLaw.value = { ...item };

  modalVisible.value = true;
}

function onPageChange(page) {
  currentPage.value = page;
  getListData();
}

function onPageSizeChange(size) {
  pageSize.value = size;
  currentPage.value = 1;
  getListData();
}

function highlightText(text, ...keywords) {
  // 支持传入数组
  if (Array.isArray(keywords[0])) keywords = keywords[0];
  if (!text) return "";
  if (!keywords.some((kw) => !!kw)) return text;
  let result = text;
  keywords.filter(Boolean).forEach((kw) => {
    const reg = new RegExp(kw.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi");
    result = result.replace(
      reg,
      (match) => `<span class='highlight'>${match}</span>`
    );
  });
  return result;
}

// 滚动提示逻辑
const lawContentRefs = reactive({});
const isOverflowMap = reactive({});
function setLawContentRef(el, id) {
  if (el) {
    lawContentRefs[id] = el;
    nextTick(() => {
      isOverflowMap[id] = el.scrollHeight > el.clientHeight;
    });
  }
}

// 弹框提交
function handleModalSubmit(data) {
  // 新增或编辑成功后刷新列表
  getListData();
}

function handleDelete(item) {
  ElMessageBox.confirm("确定要删除这条法律法规吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const res = await deleteLaw(item.id);
        if (res.code === 200) {
          ElMessage.success("删除成功");
          getListData();
        }
      } catch (error) {
        ElMessage.error(error.message);
      }
    })
    .catch(() => {});
}

function formatDate(dateStr) {
  if (!dateStr) return "";
  return dateStr.split(" ")[0].split("T")[0];
}
</script>

<style scoped>
@import "./index.scss";
</style>
